<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="工单编码" prop="workorderCode">
        <el-input
          v-model="queryParams.workorderCode"
          placeholder="请输入工单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单名称" prop="workorderName">
        <el-input
          v-model="queryParams.workorderName"
          placeholder="请输入工单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="sourceCode">
        <el-input
          v-model="queryParams.sourceCode"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户编码" prop="clientCode">
        <el-input
          v-model="queryParams.clientCode"
          placeholder="请输入客户编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="需求日期" prop="requestDate">
        <el-date-picker
          clearable
          v-model="queryParams.requestDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择需求日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="工单类型" prop="workorderType">
        <el-select
          v-model="queryParams.workorderType"
          placeholder="请选择工单类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.workorder_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ruoyidata:workorder:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyidata:workorder:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyidata:workorder:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ruoyidata:workorder:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="workorderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单编码" align="center" prop="workorderCode">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">{{
            scope.row.workorderCode
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="工单名称" align="center" prop="workorderName" />
      <el-table-column label="工单类型" align="center" prop="workorderType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.workorder_type"
            :value="scope.row.workorderType"
          />
        </template>
      </el-table-column>
      <el-table-column label="来源类型" align="center" prop="orderSource">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.order_source"
            :value="scope.row.orderSource"
          />
        </template>
      </el-table-column>
      <el-table-column label="工单来源" align="center" prop="sourceCode" />
      <el-table-column label="产品物料编号" align="center" prop="productCode" />
      <el-table-column label="产品物料名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="productSpc" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="生产数量" align="center" prop="quantity" />
      <el-table-column
        label="已生产数量"
        align="center"
        prop="quantityProduced"
      />
      <el-table-column label="调整数量" align="center" prop="quantityChanged" />
      <el-table-column
        label="已排产数量"
        align="center"
        prop="quantityScheduled"
      />
      <el-table-column label="客户名称" align="center" prop="clientName" />
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="需求日期"
        align="center"
        prop="requestDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requestDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyidata:workorder:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyidata:workorder:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleCheck(scope.row)"
            >确认</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <!-- 左列 -->
          <el-col :span="12">
            <el-form-item label="工单名称" prop="workorderName">
              <el-input
                v-model="form.workorderName"
                placeholder="请输入工单名称"
              />
            </el-form-item>

            <el-form-item label="来源类型" prop="orderSource">
              <el-radio-group
                v-model="form.orderSource"
                class="radio-group-compact"
              >
                <el-radio
                  v-for="dict in dict.type.order_source"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="订单编号"
              prop="sourceCode"
              v-if="form.orderSource == 'ORDER'"
            >
              <el-input
                v-model="form.sourceCode"
                placeholder="请输入订单编号"
              />
            </el-form-item>

            <el-form-item label="工单类型" prop="workorderType">
              <el-select
                v-model="form.workorderType"
                placeholder="请选择"
                class="w-full"
              >
                <el-option
                  v-for="dict in dict.type.workorder_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="需求日期" prop="requestDate">
              <el-date-picker
                v-model="form.requestDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <!-- 右列 -->
          <el-col :span="12">
            <el-form-item label="产品选择" prop="productName">
              <el-select
                v-model="form.productId"
                placeholder="请选择产品"
                @change="handleProductChange"
                class="w-full"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.itemId"
                  :label="item.itemName"
                  :value="item.itemId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="form.productCode" disabled />
            </el-form-item>

            <el-form-item label="规格型号" prop="productSpc">
              <el-input v-model="form.productSpc" disabled />
            </el-form-item>

            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" disabled />
            </el-form-item>

            <el-form-item label="工单数量" prop="quantity">
              <el-input-number
                v-model="form.quantity"
                :min="1"
                controls-position="right"
                class="w-full"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 客户信息（条件显示） -->
        <div v-if="form.orderSource == 'ORDER'" class="client-section">
          <el-divider content-position="left">客户信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户编号" prop="clientId">
                <el-select
                  v-model="form.clientId"
                  placeholder="请选择客户"
                  @change="handleClientChange"
                  class="w-full"
                >
                  <el-option
                    v-for="item in clientOptions"
                    :key="item.clientId"
                    :label="item.clientCode"
                    :value="item.clientId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="clientName">
                <el-input v-model="form.clientName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看生产工单 -->
    <el-dialog
      title="查看生产工单"
      :visible.sync="show"
      width="900px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <!-- 左列 -->
          <el-col :span="12">
            <el-form-item label="工单名称" prop="workorderName">
              <el-input
                v-model="form.workorderName"
                placeholder="请输入工单名称"
              />
            </el-form-item>

            <el-form-item label="来源类型" prop="orderSource">
              <el-radio-group
                v-model="form.orderSource"
                class="radio-group-compact"
              >
                <el-radio
                  v-for="dict in dict.type.order_source"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="订单编号"
              prop="sourceCode"
              v-if="form.orderSource == 'ORDER'"
            >
              <el-input
                v-model="form.sourceCode"
                placeholder="请输入订单编号"
              />
            </el-form-item>

            <el-form-item label="工单类型" prop="workorderType">
              <el-select
                v-model="form.workorderType"
                placeholder="请选择"
                class="w-full"
              >
                <el-option
                  v-for="dict in dict.type.workorder_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="需求日期" prop="requestDate">
              <el-date-picker
                v-model="form.requestDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <!-- 右列 -->
          <el-col :span="12">
            <el-form-item label="产品选择" prop="productId">
              <el-select
                v-model="form.productId"
                placeholder="请选择产品"
                @change="handleProductChange"
                class="w-full"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.itemId"
                  :label="item.itemName"
                  :value="item.itemId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="form.productCode" disabled />
            </el-form-item>

            <el-form-item label="规格型号" prop="productSpc">
              <el-input v-model="form.productSpc" disabled />
            </el-form-item>

            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" disabled />
            </el-form-item>

            <el-form-item label="工单数量" prop="quantity">
              <el-input-number
                v-model="form.quantity"
                :min="1"
                controls-position="right"
                class="w-full"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 客户信息（条件显示） -->
        <div v-if="form.orderSource == 'ORDER'" class="client-section">
          <el-divider content-position="left">客户信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户编号" prop="clientId">
                <el-select
                  v-model="form.clientId"
                  placeholder="请选择客户"
                  @change="handleClientChange"
                  class="w-full"
                >
                  <el-option
                    v-for="item in clientOptions"
                    :key="item.clientId"
                    :label="item.clientCode"
                    :value="item.clientId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="clientName">
                <el-input v-model="form.clientName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWorkorder,
  getWorkorder,
  delWorkorder,
  addWorkorder,
  updateWorkorder,
} from "@/api/ruoyidata/workorder";

import { listItem } from "@/api/ruoyidata/item"; // 添加物料产品接口

import { listClient } from "@/api/ruoyidata/client"; //客户选择

export default {
  name: "Workorder",
  dicts: ["status", "workorder_type", "order_source"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产工单表格数据
      workorderList: [],
      productOptions: [], // 新增产品选项列表
      clientOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      show: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workorderCode: null,
        workorderName: null,
        sourceCode: null,
        productCode: null,
        productName: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        workorderType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        workorderName: [
          { required: true, message: "工单名称不能为空", trigger: "blur" },
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "change" },
        ],
        orderSource: [
          { required: true, message: "订单编号不能为空", trigger: "change" },
        ],
        quantity: [
          { required: true, message: "工单数量不能为空", trigger: "blur" },
        ],
        requestDate: [
          { required: true, message: "需求日期不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getProductList();
    this.getClientList();
  },
  methods: {
    //物料产品选择
    getProductList() {
      listItem({ pageSize: 9999 }).then((response) => {
        this.productOptions = response.rows.map((item) => ({
          itemId: item.itemId,
          itemName: item.itemName,
          itemCode: item.itemCode, // 确保接口返回
          itemSpc: item.specification, // 确保接口返回
          unitOfMeasure: item.unitOfMeasure, // 确保接口返回
        }));
      });
    },
    //选择客户
    getClientList() {
      listClient({ pageSize: 9999 }).then((response) => {
        this.clientOptions = response.rows.map((item) => ({
          clientId: item.clientId,
          clientName: item.clientName,
          clientCode: item.clientCode,
        }));
      });
    },
    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      listWorkorder(this.queryParams).then((response) => {
        this.workorderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.show = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        ancestors: null,
        status: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        batchCode: null,
        finishDate: null,
        workorderType: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
      };
      this.resetForm("form");
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      this.form = {
        workorderId: row.workorderId,
        workorderCode: row.workorderCode,
        workorderName: row.workorderName,
        orderSource: row.orderSource,
        sourceCode: row.sourceCode,
        productId: row.productId,
        productCode: row.productCode,
        productName: row.productName,
        productSpc: row.productSpc,
        unitOfMeasure: row.unitOfMeasure,
        quantity: row.quantity,
        quantityProduced: row.quantityProduced,
        quantityChanged: row.quantityChanged,
        quantityScheduled: row.quantityScheduled,
        clientId: row.clientId,
        clientCode: row.clientCode,
        clientName: row.clientName,
        requestDate: row.requestDate,
        parentId: row.parentId,
        requestDate: row.requestDate,
        ancestors: row.ancestors,
        status: row.status,
        remark: row.remark,
        batchCode: row.batchCode,
        finishDate: row.finishDate,
        workorderType: row.workorderType,
        vendorId: row.vendorId,
        vendorCode: row.vendorCode,
        vendorName: row.vendorName,
      };
      this.show = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.workorderId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const workorderId = row.workorderId || this.ids;
      getWorkorder(workorderId).then((response) => {
        this.form = response.data;
        // 新增：设置产品ID以正确回显选择框
        this.form.productId = response.data.productId;
        // 新增：设置客户ID以正确回显选择框
        this.form.clientId = response.data.clientId;
        this.open = true;
        this.title = "修改生产工单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.workorderId != null) {
            updateWorkorder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWorkorder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const workorderIds = row.workorderId || this.ids;
      this.$modal
        .confirm('是否确认删除生产工单编号为"' + workorderIds + '"的数据项？')
        .then(function () {
          return delWorkorder(workorderIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleCheck(row) {
      updateWorkorder({
        workorderId: row.workorderId,
        status: "CONFIRMED",
      }).then((response) => {
        this.$modal.msgSuccess("确认成功");
        this.getList();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "ruoyidata/workorder/export",
        {
          ...this.queryParams,
        },
        `workorder_${new Date().getTime()}.xlsx`
      );
    },
    // 新增产品选择变化处理
    handleProductChange(productId) {
      const selectedProduct = this.productOptions.find(
        (item) => item.itemId === productId
      );
      if (selectedProduct) {
        this.form.productId = selectedProduct.itemId;
        this.form.productCode = selectedProduct.itemCode;
        this.form.productName = selectedProduct.itemName;
        this.form.productSpc = selectedProduct.itemSpc;
        this.form.unitOfMeasure = selectedProduct.unitOfMeasure;
      }
    },
    handleClientChange(clientId) {
      const selectedProduct = this.clientOptions.find(
        (item) => item.clientId === clientId
      );
      if (selectedProduct) {
        this.form.clientId = selectedProduct.clientId;
        this.form.clientCode = selectedProduct.clientCode;
        this.form.clientName = selectedProduct.clientName;
      }
    },
  },
};
</script>
